package com.nine.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nine.common.entity.*;
import com.nine.common.tool.AliyunOss;
import com.nine.common.tool.SnowflakeIdGenerator;
import com.nine.common.tool.ResponseResult;
import com.nine.system.mapper.ChangeInfoMapper;
import com.nine.system.mapper.EngineerMapper;
import com.nine.system.mapper.UserInfoMapper;
import com.nine.system.mapper.AuditMapper;
import com.nine.system.service.AuditService;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @ClassName: AuditServiceImpl
 * @Author: luodeng
 * @Date: 2023/6/6 9:14
 * @Version: 1.0
 */
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private AuditMapper mapper;

    @Autowired
    private EngineerMapper engineerMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AliyunOss aliyunOss;
    @Autowired
    private ChangeInfoMapper changeInfoMapper;
    @Autowired
    private SendMessage sendMessage;

    @Override
    public ResponseResult admit(String auditName,
                                String auditPhone,
                                String auditDescription,
                                String auditExperience,
                                MultipartFile auditIdcard,
                                String auditProvince,
                                String auditCity,
                                String auditArea) {
        String fileName = auditIdcard.getOriginalFilename();
        String fileExtension = null;
        File file = null;
        try {
            file = File.createTempFile("temp", null);
            FileCopyUtils.copy(auditIdcard.getBytes(), file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (fileName != null) {
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                fileExtension = fileName.substring(dotIndex);
            }
        }
        fileName = auditPhone+fileExtension;
        AuditForm auditForm = new AuditForm();
        auditForm.setAuditName(auditName);
        auditForm.setAuditPhone(auditPhone);
        auditForm.setAuditDescription(auditDescription);
        auditForm.setAuditExperience(auditExperience);
        auditForm.setAuditProvince(auditProvince);
        auditForm.setAuditCity(auditCity);
        auditForm.setAuditArea(auditArea);
        auditForm.setAuditIdcard(fileName);
        aliyunOss.handleUploadAudit(file,fileName);
        mapper.insert(auditForm);
        return ResponseResult.ok("上传成功");
    }


    //平台审核人员 处理申请
    @Override
    public ResponseResult handleAudit(int id,int result) {
        LambdaQueryWrapper<AuditForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuditForm::getAuditId,id);
        AuditForm auditForm = mapper.selectOne(wrapper);


        if(result==1){
            auditForm.setAuditStatus(1);
            mapper.updateById(auditForm);//修改申请表中的审核状态

            //建立user账户
            UserInfo newUser = new UserInfo();
            newUser.setUsername('E'+auditForm.getAuditPhone());
            newUser.setPassword(DigestUtils.md5DigestAsHex(auditForm.getAuditPhone().substring(auditForm.getAuditPhone().length()-6).getBytes()));
            newUser.setStatus(1);
            newUser.setRoleId(103);
            newUser.setPhone(auditForm.getAuditPhone());
            newUser.setBalance(new BigDecimal(0));
            userInfoMapper.insert(newUser);
            Long generatedId = newUser.getUid();

            EngineerForm newEngineer = new EngineerForm();
            newEngineer.setEngineerId(generatedId);
            newEngineer.setEngineerName(auditForm.getAuditName());
            newEngineer.setEngineerPhone(auditForm.getAuditPhone());

            newEngineer.setEngineerProvince(auditForm.getAuditProvince());
            newEngineer.setEngineerCity(auditForm.getAuditCity());
            newEngineer.setEngineerArea(auditForm.getAuditArea());

            newEngineer.setEngineerDescription(auditForm.getAuditDescription());

            engineerMapper.insert(newEngineer);


        }else{
            auditForm.setAuditStatus(2);
            mapper.updateById(auditForm);

            //发送被拒绝短信
            try {
                sendMessage.SendRejectionInfo(auditForm.getAuditPhone());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ResponseResult.ok("该申请已审核");
    }

    //查看所有申请表  使用对象是平台审核人员
    @Override
    public ResponseResult getAll(int page,int limit) {
        //todo
        IPage<AuditForm> iPage = new Page<>(page,limit);
        IPage<AuditForm> iPage1 = mapper.selectPage(iPage, null);
        List<AuditForm> records = iPage1.getRecords();
        long count = iPage1.getTotal();
        return ResponseResult.okc(records,count);
    }

    @Override
    public ResponseResult getOne(int id) {
        LambdaQueryWrapper<AuditForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuditForm::getAuditId,id);
        return ResponseResult.ok(mapper.selectOne(wrapper));
    }

    @Override
    public ResponseResult find(String auditStatus,int page,int limit) {
        IPage<AuditForm> page1 = new Page<>(page,limit);

        if(Integer.parseInt(auditStatus)==4){

            IPage<AuditForm> iPage = mapper.selectPage(page1, null);
            List<AuditForm> records = iPage.getRecords();
            List<AuditFormVO> list = new ArrayList<>();
            String auditAddress=null;
            for(int i=0;i< records.size();i++){
                AuditForm auditForm = records.get(i);

                String auditProvince = auditForm.getAuditProvince();
                String auditCity = auditForm.getAuditCity();
                String auditArea = auditForm.getAuditArea();

                auditAddress = auditProvince+ " " + auditCity + " " + auditArea;
                AuditFormVO auditFormVO = new AuditFormVO(auditForm, auditAddress);
                list.add(auditFormVO);
            }
            long total = iPage.getTotal();
            return ResponseResult.okc(list,total);

        }else{
            LambdaQueryWrapper<AuditForm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AuditForm::getAuditStatus,Integer.parseInt(auditStatus));
            IPage<AuditForm> iPage = mapper.selectPage(page1,wrapper);
            List<AuditForm> records = iPage.getRecords();
            long total = iPage.getTotal();

            List<AuditFormVO> list = new ArrayList<>();
            String auditAddress=null;
            for(int i=0;i< records.size();i++){
                AuditForm auditForm = records.get(i);

                String auditProvince = auditForm.getAuditProvince();
                String auditCity = auditForm.getAuditCity();
                String auditArea = auditForm.getAuditArea();

                auditAddress = auditProvince+ " " + auditCity + " " + auditArea;
                AuditFormVO auditFormVO = new AuditFormVO(auditForm, auditAddress);
                list.add(auditFormVO);
            }

            return ResponseResult.okc(list,total);
        }
    }

    @Override
    public ResponseResult getWork(int page, int limit) {
        IPage<AuditForm> page1 = new Page<>(page,limit);
        LambdaQueryWrapper<AuditForm> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(AuditForm::getAuditStatus,0);
        IPage<AuditForm> iPage = mapper.selectPage(page1, wrapper);

        long total = iPage.getTotal();
        List<AuditForm> records = iPage.getRecords();

        String auditAddress = null;
        List<AuditFormVO> list = new ArrayList<>();
        for(int i=0;i<records.size();i++){
            AuditForm auditForm = records.get(i);

            String auditProvince = auditForm.getAuditProvince();
            String auditCity = auditForm.getAuditCity();
            String auditArea = auditForm.getAuditArea();

            auditAddress = auditProvince+ " " + auditCity + " " + auditArea;
            AuditFormVO auditFormVO = new AuditFormVO(auditForm, auditAddress);
            list.add(auditFormVO);
        }

        return ResponseResult.okc(list,total);
    }

    @Override
    public ResponseResult getAuditStatusCount() {
        AuditStatusCount auditStatusCount = mapper.getAuditStatusCount();
        return ResponseResult.ok(auditStatusCount);
    }

    @Override
    public ResponseResult getPie() {
        List<AuditForm> auditForms = mapper.selectList(null);
        return ResponseResult.ok(auditForms);
    }

    @Override
    public ResponseResult getUnhandleChanges(int page,int limit) {
        IPage<ChangeForm> iPage = new Page<>(page,limit);
        LambdaQueryWrapper<ChangeForm> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ChangeForm::getChangeStatus,0);
        IPage<ChangeForm> iPage1 = changeInfoMapper.selectPage(iPage, wrapper);
        List<ChangeForm> records = iPage1.getRecords();
        long total = iPage1.getTotal();
        return ResponseResult.okc(records,total);
    }

    @Override
    public ResponseResult findChanges(String auditStatus, int page, int limit) {

        IPage<ChangeForm> page1 = new Page<>(page, limit);

        if (Integer.parseInt(auditStatus) == 4) {

            IPage<ChangeForm> iPage = changeInfoMapper.selectPage(page1, null);
            List<ChangeForm> records = iPage.getRecords();

            long total = iPage.getTotal();
            return ResponseResult.okc(records, total);

        } else {
            LambdaQueryWrapper<ChangeForm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChangeForm::getChangeStatus, Integer.parseInt(auditStatus));
            IPage<ChangeForm> iPage = changeInfoMapper.selectPage(page1, wrapper);
            List<ChangeForm> records = iPage.getRecords();
            long total = iPage.getTotal();


            return ResponseResult.okc(records, total);

        }
    }

    @Override
    public ResponseResult handleChange(int id, int result) {

        ChangeForm changeForm = changeInfoMapper.selectOne(new LambdaQueryWrapper<ChangeForm>().eq(ChangeForm::getChangeId, id));
        System.out.println(changeForm);
        if(result==1){
            changeForm.setChangeStatus(1);

            EngineerForm engineerForm = engineerMapper.selectOne(new LambdaQueryWrapper<EngineerForm>().eq(EngineerForm::getEngineerId, changeForm.getEngineerId()));
            System.out.println("变动前:"+engineerForm);
            engineerForm.setEngineerArea(changeForm.getChangeArea());
            engineerForm.setEngineerProvince(changeForm.getChangeProvince());
            engineerForm.setEngineerCity(changeForm.getChangeCity());
            engineerForm.setEngineerPhone(changeForm.getChangePhone());
            engineerForm.setEngineerDescription(changeForm.getChangeDescription());
            System.out.println("变动后:"+engineerForm);
            changeInfoMapper.updateById(changeForm);
            engineerMapper.updateById(engineerForm);
            return ResponseResult.ok("通过成功");
        }

        changeForm.setChangeStatus(2);
        changeInfoMapper.updateById(changeForm);
        return ResponseResult.ok("拒绝成功");
    }

    @Override
    public ResponseResult getChangePie() {

        return ResponseResult.ok(changeInfoMapper.getChangePie());
    }

}
